<?php
/*
Copyright 2011 Erick Martínez Sámano

This file is part of PHP Quick Calendar E.

PHP Quick Calendar E is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

PHP Quick Calendar E is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

<http://www.gnu.org/licenses/>

Some code in this file was taken from PHP Quick Calendar, and the copyright of it belongs to Bernard Peh
<http://www.azhowto.com>
*/
defined( '_JEXEC' ) or die( 'Restricted access' );
class qcalendareBase{
	var $daysInMonth;
	var $weeksInMonth;
	var $cell;
	var $firstDay;
	var $month;
	var $year;
	var $day;
	var $cat_id;
	var $today;
	var $links;
	var $header;
	var $nextMonth;
	var $prevMonth;
	var $lYear;
	var $pYear;

	function __construct($day='', $month='', $year='',$createLinks=true,$catid=0){
		$app=&JFactory::getApplication();
		$offset =&$app->getCfg('offset');
		date_default_timezone_set($offset);
		$this->year  = ($year)? (int)$year : date('Y');
		($month>12)? $month=12 : '';
		$this->month = ($month)? (int)$month : date('n');
		$this->cat_id = (int)$catid;
		$this->daysInMonth = date("t",mktime(0,0,0,$this->month,1,$this->year));
		($day>$this->daysInMonth)? $day=$this->daysInMonth : '';
		$this->day = ($day)? (int)$day : date('j');
		$this->today = array('day'=>date('j'), 'month'=>date('n'), 'year'=>date('Y'));
		$this->cell = array();
		$this->links = array();
		$this->view = array();
		// get first day of the month
		$this->firstDay = date("w", mktime(0,0,0,$this->month,1,$this->year));
		$this->weeksInMonth = ceil(($this->firstDay + $this->daysInMonth)/7);
		$this->fillArray();
		$this->buildNavigationVar();
		if ($createLinks) {$this->createLinks();}
	}
	//para algunas vistas, no se necesita todo lo que se selecciona aquí, para small sólo se necesita active,type, refdate y enddate
	function createLinks() {
		$db =& JFactory::getDBO();
		$m=$this->month;$y=$this->year;
		$dT = "{$y}-{$m}-{$this->daysInMonth}";
		$qry = "SELECT q.id, q.hr, q.min, q.thr, q.tmin, q.refdate, q.enddate, q.created, q.type, q.link, q.url, q.short_desc, q.short_desc_image, c.short_desc as category, c.short_desc_image as cat_short_img, c.active as cat_act, c.id as cat_id FROM #__qcalendar as q, #__qcalendar_category as c WHERE IF ($this->cat_id != 0, c.id = '$this->cat_id', 1) AND q.category_id=c.id AND q.active='1' AND IF (q.type!=0 && q.enddate != '0000-00-00',q.refdate<=q.enddate AND (YEAR(q.enddate)>'$y' || (MONTH(q.enddate)>='$m'  && YEAR(q.enddate)='$y') ),1) AND (q.refdate <= '$dT') AND (  (q.type='0' && MONTH(q.refdate)='$m' && YEAR(q.refdate)='$y') OR (((q.type='1' && MONTH(q.refdate)='$m') || q.type='2') && (YEAR(q.enddate)!='$y' || MONTH(q.enddate)!='$m' || DAY(q.refdate)<=DAY(q.enddate))) OR (q.type='3') OR (q.type='4' && ( q.enddate='0000-00-00' || q.enddate>'$y-$m-7' || (DAYOFWEEK(q.refdate)-$this->firstDay +7)%7 <=DAY(q.enddate)) ) ) order by q.hr asc, q.min asc";
		$db->setQuery($qry);
		$this->links = $db->loadObjectList();
		return $this->links;
	}
	/**
	 * The calendar is created using a 2-D array. This function fills the array with the right values. 0 is a sunday.
	 *
	 * @param Int $firstColumn
	 */
	function fillArray($firstColumn=0) {
		// create a 2-d array
		$counter = $firstColumn;
		if ($firstColumn > $this->firstDay) {
			$counter = -(7 - $firstColumn);
			$this->weeksInMonth++;
		}
		
		for($i=0; $i<$this->weeksInMonth; $i++) {
			// if days in month exceeded, break out of loop
			if ($counter - $this->firstDay + 1 > $this->daysInMonth) {
				$this->weeksInMonth--;
			}
				
			for($j=0;$j<7;$j++) {				
				$counter++;
				$this->cell[$i][$j]['value'] = $counter; 
				// offset the days
				$this->cell[$i][$j]['value'] -= $this->firstDay;
				if (($this->cell[$i][$j]['value'] < 1) || ($this->cell[$i][$j]['value'] > $this->daysInMonth)){	
					$this->cell[$i][$j]['value'] = '';
				}
			}
		}
	}
	function buildNavigationVar() {
		$this->header = JText::_('COM_PQCE_3M'.strftime("%m",mktime(0,0,0,$this->month,1,$this->year))).' '.$this->year;
		$this->nextMonth = $this->month+1;
		$this->prevMonth = $this->month-1;

		switch($this->month) {
			case 1:
	   			$this->lYear = $this->year;
   				$this->pYear = $this->year-1;
   				$this->nextMonth=2;
   				$this->prevMonth=12;
   				break;
  			case 12:
   				$this->lYear = $this->year+1;
   				$this->pYear = $this->year;
   				$this->nextMonth=1;
   				$this->prevMonth=11;
      			break;
  			default:
      			$this->lYear = $this->year;
	   			$this->pYear = $this->year;
    	  		break;
  		}
	$this->nextMonth=sprintf('%02s',$this->nextMonth);
	$this->prevMonth=sprintf('%02s',$this->prevMonth);
	}
	function createBody(){
		$params = JComponentHelper::getParams("com_pqce");$dir=$params->get('images_dir');
		$rn=count($this->links);
		$firstWDay = array();
		$compdate="{$this->year}-{$this->month}-";
		for ($r=0; $r < $rn; $r++){
			$row = &$this->links[$r];
			if ($row->type==4){$daySem[$r]=$this->getDay($row->refdate);$firstWDay[$r]=($daySem[$r]-$this->firstDay +7)%7;}
			$haq[$r] = ($row->cat_short_img && $row->cat_act);
		}
		unset($daySem);
		// start rendering table
		for ($i=0;$i<$this->weeksInMonth;$i++) {
			for ($j=0;$j<7;$j++) {
				$val = &$this->cell[$i][$j]['value'];
				// check if if is today
				if (($this->today['day'] == $val) && ($this->today['month'] == $this->month) && ($this->today['year'] == $this->year)) {
					$this->cell[$i][$j]['isToday'] = 1;
				}
				// else normal day
				else {
					$this->cell[$i][$j]['isToday'] = 0;
				}
				// init defaults
				$this->cell[$i][$j]['link'] = 'none';
				$this->cell[$i][$j]['day'] = &$val; 
				$this->cell[$i][$j]['short_desc'][] = '';
				$this->cell[$i][$j]['short_desc_images'][] =''; //Quiero usar tambien la img de la catego4this->cell
				$this->cell[$i][$j]['hora'][]='';
				if ($val==''){continue;} //don't waste time
				// if days with link
				$count = 0;
				for ($r=0; $r < $rn; $r++){
				$row = &$this->links[$r]; $f=explode('-',$row->refdate); $day=(int)$f[2];
				//$endD=explode('-',$row->enddate);
				unset($f);
				if ( ($day == $val && $row->type<3) || ( ($row->type==3  || ($row->type==4 && ($val-$firstWDay[$r])%7==0)) && $this->leqDate($row->refdate,$compdate.$val) && $this->leqDate($compdate.$val,$row->enddate) ) ){
					$hr=sprintf('%02s', $row->hr);$min=sprintf('%02s', $row->min);$short_desc=ucfirst($row->short_desc);
					$this->cell[$i][$j]['hora'][$count]="$hr:$min";				
							switch ($row->link) {		
								case 'url':
									$this->cell[$i][$j]['link'] = 'url';
									$this->cell[$i][$j]['short_desc'][$count] = "<a title='$hr".":".$min."' href=\"{$row->url}\" target='_blank'>{$short_desc}</a>";
									$this->cell[$i][$j]['short_desc_images'][$count] = ($row->short_desc_image) ? "<a href=\"$row->url\" target='_blank'><img src=\"".JURI::root().$row->short_desc_image."\" /></a>" : '';break;
								
								case 'div':
									$this->cell[$i][$j]['link'] = 'div';
									$this->cell[$i][$j]['short_desc'][$count] = "<a  title='$hr".':'.$min."'"." href=\"".JRoute::_("index.php?option=com_pqce&f=$val.$this->month.$this->year&e=$row->id")."\">$short_desc</a>";
									$this->cell[$i][$j]['short_desc_images'][$count] = ($row->short_desc_image) ? "<a href=\"".JRoute::_("index.php?option=com_pqce&f=$val.$this->month.$this->year&e=$row->id")."\" /><img src=\"".JURI::root().$row->short_desc_image."\" /></a>" : '';break;
								
								default:
									$this->cell[$i][$j]['short_desc'][$count] = "<a title='$hr".":".$min."' class='nolink'>$short_desc</a>";
									if ($row->short_desc_image){
$this->cell[$i][$j]['short_desc_images'][$count] = "<img src=\"".JURI::root().$row->short_desc_image."\" />";}break;
						}
					($haq[$r])? $this->cell[$i][$j]['short_desc_images'][$count] .= "<img title='$row->category' src='".JURI::root().$row->cat_short_img."' />" : '';
						$count++;
					}
			}
				
			}
		}
		return $this->cell;
	}

	function createHrefHeader($view='') {
		$v= ($view)? "&view=".$view:'';
		$href = array(); //ME FALTA QUÉ HACER CON LAS CATEGORÍAS
		$href['prevYear'] = JRoute::_("index.php?option=com_pqce$v&month=$this->month&year=".($this->year-1));
		$href['prevMonth'] = JRoute::_("index.php?option=com_pqce$v&month=$this->prevMonth&year=$this->pYear");
		$href['header'] = $this->header;
		$href['nextMonth'] = JRoute::_("index.php?option=com_pqce$v&month=$this->nextMonth&year=$this->lYear");
		$href['nextYear'] = JRoute::_("index.php?option=com_pqce$v&month=$this->month&year=".($this->year+1));
		return $href;
	}

	function createLongDescDay($d=0,$m=1,$y=1982,$c=0){
		($d==0)? $d=$this->day : '';
		$db =& JFactory::getDBO();
		$qry = "SELECT q.refdate, q.link, q.hr, q.min, q.thr, q.tmin, q.url, c.active as cat_act, c.short_desc as category, q.short_desc, q.long_desc, q.long_desc_image, q.short_desc_image, c.short_desc_image as cshort_image FROM #__qcalendar as q, #__qcalendar_category as c WHERE IF ($c != 0, q.category_id = '$c', 1) AND q.category_id=c.id AND q.active='1' AND IF (q.type!=0 && q.enddate != '0000-00-00',q.refdate<=q.enddate AND q.enddate>='$y-$m-$d',1)  AND q.refdate<='$y-$m-$d' AND ( q.type='3' || (q.type='4' && DAYOFWEEK(q.refdate)=DAYOFWEEK('$y-$m-$d')) || (DAY(q.refdate)='$d' && ((q.type='0' && MONTH(q.refdate)='$m' && YEAR(q.refdate)='$y') || (q.type='1' && MONTH(q.refdate)='$m') || q.type='2')) ) order by q.hr asc, q.min asc";
		$db->setQuery($qry);
		return $db->loadObjectList();
	}
	function createLongDescEvent($e=0){
		if ($e==0){return null;}
		$db =& JFactory::getDBO();
		$qry = "SELECT * FROM #__qcalendar WHERE id='".(int)$e."' AND active='1'";
		$db->setQuery($qry);
		return $db->loadObjectList();
	}
	/*
	*Regresa el día de la semana definido por $d1='YYYY-MM-DD'
	* dom =1, lun=2...
	*/
	private function getDay($d1){
		$db =& JFactory::getDBO();
		$db->setQuery("SELECT DAYOFWEEK('$d1')");
		return $db->loadResult();
	}
	/* 
	** d1<=d2?
	** d1,d2 -> 'YYYY-MM-DD'
	**
	*/
	function leqDate($d1,$d2){
		$d1=explode('-',$d1); $d2=explode('-',$d2);
		if ($d2[0]=='0000'){return true;}
		if ($d1[0]<$d2[0]){return true;}
		elseif ($d1[0]==$d2[0]){
				if ($d1[1]<$d2[1]){return true;}
				elseif ($d1[1]==$d2[1]){
					if ($d1[2]<=$d2[2]){return true;}else{return false;}
				}
			}
		return false;
	}
	function setCategoryId($cat_id) {
		$this->cat_id=(int)$cat_id;
	 }
}
